package com.wenqiner.requesttool.view;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.text.CharSequenceUtil;
import com.wenqiner.requesttool.core.business.lingyin.LingyinConstant;
import com.wenqiner.requesttool.core.business.lingyin.ParamData;
import com.wenqiner.requesttool.core.exception.CustomException;
import com.wenqiner.requesttool.core.fx.AlertTool;
import com.wenqiner.requesttool.domain.HttpResponseData;
import com.wenqiner.requesttool.util.CommonUtil;
import com.wenqiner.requesttool.util.TableUtil;
import com.wenqiner.requesttool.util.HttpUtil;
import com.wenqiner.requesttool.util.ParsePlaceholderUtil;
import com.wenqiner.requesttool.view.base.AbstractRequestLayout;
import com.wenqiner.requesttool.view.base.CommonController;
import com.wenqiner.requesttool.view.base.OuterParamProcess;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * @author rhf
 * @date 2023-02-28
 **/
public class OuterRequestController extends AbstractRequestLayout implements CommonController, OuterParamProcess {

    public static final Logger log = LoggerFactory.getLogger(OuterRequestController.class);

    @FXML
    protected GridPane paramTable;
    @FXML
    protected GridPane headerTable;

    @Override
    public void init() {
        requestId.setText(requestId());
    }

    @FXML
    protected void addParamRowsEvent(ActionEvent event) throws IOException {
        super.createTable(paramTable, super.gridPaneNextRowNum(paramTable));
    }

    @FXML
    protected void addHeaderRowsEvent(ActionEvent event) throws IOException {
        super.createTable(headerTable, super.gridPaneNextRowNum(headerTable));
    }

    @FXML
    protected TextArea requestOriginalData;
    @FXML
    protected TextArea requestData;
    @FXML
    protected TextArea responseOriginalData;
    @FXML
    protected TextArea responseData;
    @FXML
    protected ComboBox<String> protocolType;
    @FXML
    protected TextField requestUrl;

    @FXML
    protected TextField requestId;

    @FXML
    protected void refreshEvent(ActionEvent event) {
        requestId.setText(requestId());
    }

    @FXML
    protected void sendRequest(ActionEvent event) throws IOException {
        //获取全部系统参数
        Map<String, String> paramMap = TableUtil.parseHeader(paramTable);
        //获取全部header
        Map<String, String> headerMap = TableUtil.parseHeader(headerTable);
        //获取地址
        String requestPath = String.join("", protocolType.getValue(), requestUrl.getText());
        //获取请求参数
        String text = requestOriginalData.getText();
        if (CharSequenceUtil.isBlank(text)) {
            AlertTool.showError(" 请输入请求报文");
            return;
        }
        String platformNo = headerMap.get(LingyinConstant.PARTNER_ID);
        if (CharSequenceUtil.isBlank(platformNo)) {
            AlertTool.showError(LingyinConstant.PARTNER_ID + " is required.");
            return;
        }
        String merchantPrivateKey = paramMap.get(LingyinConstant.MERCHANT_PRIVATE_KEY);
        if (CharSequenceUtil.isBlank(merchantPrivateKey)) {
            AlertTool.showError(LingyinConstant.MERCHANT_PRIVATE_KEY + " is required.");
            return;
        }
        String publicKey = paramMap.get(LingyinConstant.PLATFORM_PUBLIC_KEY);
        if (CharSequenceUtil.isBlank(publicKey)) {
            AlertTool.showError(LingyinConstant.PLATFORM_PUBLIC_KEY + " is required.");
            return;
        }
        String requestId = headerMap.get(LingyinConstant.REQUEST_ID);
        if (CharSequenceUtil.isBlank(requestId)) {
            AlertTool.showError(LingyinConstant.REQUEST_ID + " is required.");
            return;
        }
        headerMap.keySet().forEach(key -> {
            try {
                headerMap.put(key, ParsePlaceholderUtil.parseMethodOuter(headerMap.get(key)));
            } catch (Exception e) {
            }
        });
        String timestamp = headerMap.get(LingyinConstant.TIME);
        headerMap.put(LingyinConstant.TIME, Base64Encoder.encode(timestamp));

        String requestDataEncrypt = null;
        try {
            requestDataEncrypt = requestEncrypt(publicKey, merchantPrivateKey, ParsePlaceholderUtil.parseMethodOuter(text), timestamp);
        } catch (Exception e) {
            log.error("参数加密异常,error msg:[{}],\ne:{}", e.getMessage(), e);
            AlertTool.showError("请求参数加密失败");
            return;
        }
        HttpResponseData<String> httpResponseData = null;
        try {
            requestData.setText(requestDataEncrypt);
            httpResponseData = HttpUtil.doPost(requestPath, headerMap, requestDataEncrypt);
        } catch (CustomException e) {
            AlertTool.showError(e.getMsg());
            return;
        }
        responseOriginalData.setText(httpResponseData.getData());
        try {
            ParamData paramData = responseDecrypt(publicKey, merchantPrivateKey, httpResponseData);
            responseData.setText(CommonUtil.formatJson(paramData));
            AlertTool.showInformation(httpResponseData.getMsg());
        } catch (Exception e) {
            log.error("接收响应异常,error msg:[{}],\ne:{}", e.getMessage(), e);
            AlertTool.showError("解密响应报文失败");
        }

    }


    @FXML
    protected void paramFormatEvent(ActionEvent event) {
        String reqStr = requestData.getText();
        requestData.setText(CommonUtil.formatJson(reqStr));
        String oriReqStr = requestOriginalData.getText();
        requestOriginalData.setText(CommonUtil.formatJson(oriReqStr));
        String resStr = responseData.getText();
        responseData.setText(CommonUtil.formatJson(resStr));
        String oriResStr = responseOriginalData.getText();
        responseOriginalData.setText(CommonUtil.formatJson(oriResStr));
    }
}
